package com.kevin.io.jdk.bio;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author Kevin Liu
 * @date 2020/8/26 8:49 下午
 */
public class Server {

    private static ExecutorService threadPool = Executors.newCachedThreadPool();


    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8080);
        System.out.println("server start success");
        while (!serverSocket.isClosed()) {
            final Socket client = serverSocket.accept();
           // threadPool.execute(() -> {
                System.out.println(client + "connected");
                final InputStream inputStream;
                try {
                    inputStream = client.getInputStream();
                    BufferedReader bufferedReader = IoUtils.getBufferedReader(inputStream);
                    String msg;
                    while ((msg = bufferedReader.readLine()) != null) {
                        if (msg.length() == 0) {
                            break;
                        }
                        System.out.println(msg);
                    }
                     //响应结果 200
                    OutputStream outputStream = client.getOutputStream();
                    outputStream.write("HTTP/1.1 200 OK\r\n".getBytes());
                    outputStream.write("Content-Length: 11\r\n\r\n".getBytes());
                    outputStream.write("Hello World".getBytes());
                    outputStream.flush();
                }
               catch (IOException e) {
                    e.printStackTrace();
                }
            //});
        }
    }
}
